﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using LostLib.Programs;
using LostLib;

namespace CliPack.WPF
{
	/// <summary>
	/// Interaction logic for AssembliesWindow.xaml
	/// </summary>
	public partial class AssembliesWindow : Window
	{
		public AssembliesWindow()
		{
			InitializeComponent();
		}

		private void Page_Loaded(object sender, RoutedEventArgs e)
		{
			AssemblyManager.InstallApprover += new EventHandler<ApproveEventArgs<IEnumerable<AssemblyVersion>>>(AssemblyManager_InstallApprover);

			assemblies.ItemsSource = AssemblyManager.ApplicationDatabase.AssemblyInfos;
		}

		void AssemblyManager_InstallApprover(object sender, ApproveEventArgs<IEnumerable<AssemblyVersion>> e)
		{
			var message = new StringBuilder("Do you want to install the following assemblies:\n");
			foreach (var assembly in e.Subject)
				message.AppendFormat("\t{0}\n", assembly);
			e.Approved = MessageBox.Show(this, message.ToString(), "Installation", MessageBoxButton.YesNo, MessageBoxImage.Question) == MessageBoxResult.Yes;
		}

		private void CheckBox_Click(object sender, RoutedEventArgs e)
		{
			var check = sender as CheckBox;
			var name = check.Content as string;

			var version = AssemblyManager.ApplicationDatabase.AssemblyInfos.Single(assembly => assembly.AssemblyName == name);
			version.IsInstalled = check.IsChecked.GetValueOrDefault();
			check.IsChecked = version.IsInstalled;
		}

		private void Button_Click(object sender, RoutedEventArgs e)
		{
			var button = sender as Button;
			var name = button.CommandParameter as string;

			var version = AssemblyManager.ApplicationDatabase.AssemblyInfos
				.Single(assembly => assembly.AssemblyName == name)
				.LatestSuitable;

			AssemblyManager.Install(version);
		}
	}
}
